package com.tadpole.music.adapter.base;

import android.view.View;
import android.view.ViewGroup;

import androidx.collection.SparseArrayCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.tadpole.music.holder.base.BaseViewHolder;

/**
 * Created By 孙岩
 * on 2020/8/20
 */
public abstract class BaseAdapter extends RecyclerView.Adapter<BaseViewHolder>{
    protected static final int BASE_ITEM_TYPE_HEADER = 10000;
    protected static final int BASE_ITEM_TYPE_FOOTER = 30000;
    protected static final int NORMAL = 20000;

    protected SparseArrayCompat<BaseViewHolder> mHeadViews = new SparseArrayCompat<>();
    protected SparseArrayCompat<BaseViewHolder> mFootViews = new SparseArrayCompat<>();

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mHeadViews.get(viewType) != null) {return mHeadViews.get(viewType);}
        if (mFootViews.get(viewType) != null){ return mFootViews.get(viewType);}
        return createRelHolder(parent, viewType);
    }

    //子类实现
    public abstract BaseViewHolder createRelHolder(ViewGroup parent, int viewType);


    @Override
    public int getItemViewType(int position) {
        if (isHeadView(position))
        { return mHeadViews.keyAt(position);}
        if (isFootView(position))
        {return mFootViews.keyAt(position - getHeadCount() - getRelItemCount());}
        return NORMAL;
    }

    @Override
    public int getItemCount() {
        return getHeadCount() + getRelItemCount() + getFootCount();
    }

    public abstract int getRelItemCount();

    public boolean isHeadView(int position) {
        return position < getHeadCount();
    }

    public boolean isFootView(int position) {
        return position >= getHeadCount() + getRelItemCount();
    }

    public void addHeadView(BaseViewHolder holder) {
        mHeadViews.put(mHeadViews.size() + BASE_ITEM_TYPE_HEADER, holder);
    }

    public void addFootView(BaseViewHolder holder) {
        mFootViews.put(mFootViews.size() + BASE_ITEM_TYPE_FOOTER, holder);
    }

    public int getHeadCount() {
        return mHeadViews.size();
    }

    public int getFootCount() {
        return mFootViews.size();
    }

    //增加监听
    public interface OnItemClickListener {
        void onItemClick(View v, int position);
    }

    public abstract void setOnItemClickListener(OnItemClickListener listener);


    public interface OnChildClickListener{
        void onChildClick(View v, int position);
    }

    public abstract  void setOnChildClickListener(OnChildClickListener listener);

    public interface OnLongClickListener{
        void onLongClickListener(View v, int position);
    }

    public abstract  void setOnLongClickListener(OnLongClickListener listener);
}
